"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 备机事务内写转发
Case Name   : 扩展查询之在备机执行只读查询
Create At   : 2023/07/12
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.在主机创建表
    3.扩展查询之在备机执行只读查询
    4.查看日志打印
    5.环境清理，恢复参数
Expect      :
    1.修改成功
    2.创建成功
    3.执行成功
    4.日志记录libpqsw:P报文信息，不转发给主机
    5.环境清理成功，恢复参数成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import re
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != PrimarySh.get_node_num(), '非1主2备环境不执行')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_root = Node('Standby2Root')
        self.standby_dbuser = Node('Standby2DbUser')
        self.standby_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.common = Common('Standby2DbUser')
        self.common_std_root = Common('Standby2Root')
        self.table_name = 't_multi_node_write_0038'
        self.java_file = "Opengauss_SharedStorage_MultiNodeWrite_Case0038.java"
        self.target_path = os.path.join(macro.DB_MY_PATH,
                                        'JDBC_multi_node_write_0038')
        self.jar_abspath = os.path.join(self.target_path, 'postgresql.jar')
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_multi_node_write0038')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir} {self.target_path};echo $?;"
        self.logger.info(shell_cmd)
        shell_res = self.common.get_sh_result(self.standby_root, shell_cmd)
        self.assertEqual('0', shell_res.splitlines()[-1].strip(),
                         '删除目录失败')

    def test_multi_node_write(self):
        text = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(text)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute} = on')
        self.assertTrue(result, f'执行失败:{text}')
        stop_res = self.standby_sh.exec_cm_ctl('stop')
        self.logger.info(stop_res)
        self.assertIn(self.constant.cm_stop_success_msg, stop_res,
                      f'stop集群失败:{text}')
        start_res = self.standby_sh.exec_cm_ctl('start')
        self.logger.info(start_res)
        self.assertIn(self.constant.cm_start_success_msg, start_res,
                      f'start集群失败:{text}')
        time.sleep(5)
        status = self.standby_sh.exec_cm_ctl('query', '-Cv')
        self.logger.info(status)
        self.assertTrue("cluster_state   : Normal" in status, '集群状态异常')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement} = all')
        self.assertTrue(result, f'执行失败:{text}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory} = '{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{text}')

        text = "-----step2:在主机创建表;expect:创建成功-----"
        self.logger.info(text)
        sql_cmd = f'''drop table if exists {self.table_name};
            create table {self.table_name}(
            id int, name varchar(20)) with(segment=on);
            insert into {self.table_name} values(1, 'test1');'''
        sql_res = PrimarySh.execut_db_sql(sql_cmd)
        self.logger.info(sql_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      sql_res, f'执行失败:{text}')
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_res, f'执行失败:{text}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG,
                      sql_res, f'执行失败:{text}')
        time.sleep(10)

        text = "-----step3:扩展查询之在备机执行只读查询;expect:执行成功-----"
        self.logger.info(text)
        self.logger.info('-----复制java脚本至指定的主机路径-----')
        self.common_std_root.scp_file(
            self.standby_root, self.java_file, self.target_path)
        self.logger.info('-----复制jdbc jar包至指定的主机路径-----')
        self.standby_root.scp_put(macro.JDBC_PATH, self.jar_abspath)
        cmd = f'ls {self.target_path}'
        self.logger.info(cmd)
        res = self.standby_root.sh(cmd).result()
        self.logger.info(res)
        self.assertIn(self.java_file, res, f'复制java脚本失败:{text}')
        self.assertIn('postgresql.jar', res, f'复制jar包失败:{text}')
        self.logger.info('-----编译java文件-----')
        compile_cmd = f"cd {self.target_path};" \
                      f"javac -encoding utf-8 -cp {self.jar_abspath} {self.java_file}"
        self.logger.info(compile_cmd)
        compile_res = self.standby_root.sh(compile_cmd).result()
        self.logger.info(compile_res)
        self.assertNotIn('ERROR', compile_res, f'编译失败:{text}')
        self.logger.info('-----运行java预编译代码-----')
        para = f"{self.standby_dbuser.db_host}:{self.standby_dbuser.db_port}" \
               f" {self.standby_dbuser.db_name} {self.standby_dbuser.db_user}" \
               f" {self.standby_dbuser.db_password}"
        java_cmd = f"cd {self.target_path};" \
                   f"java -cp {self.jar_abspath}:{self.target_path} " \
                   f"{self.java_file[:-5]} {para} "
        self.logger.info(java_cmd)
        java_res = self.standby_root.sh(java_cmd).result()
        self.logger.info(java_res)
        self.assertIn('1 | test1', java_res, f'运行java脚本失败:{text}')
        time.sleep(5)

        text = "-----step4:查看日志打印;expect:日志记录libpqsw:P报文信息，不转发给主机-----"
        self.logger.info(text)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_res = self.common.get_sh_result(self.standby_dbuser, shell_cmd)
        self.logger.info(shell_res)
        logfile = os.path.join(self.new_log_dir, shell_res.split()[0])
        shell_cmd = f"grep {self.standby_dbuser.db_name} {logfile}"
        self.logger.info(shell_cmd)
        shell_res = self.common.get_sh_result(self.standby_dbuser, shell_cmd)
        self.assertIn(f'we find pbe new select cmdtag:SELECT, sql:select * '
                      f'from {self.table_name}', shell_res, f'执行失败:{text}')
        self.assertIn(f"[BACKEND] LOG:  execute <unnamed>: select * from "
                      f"{self.table_name}", shell_res, f'执行失败:{text}')
        expect = f"LOG:  libpqsw\(.*?\):\[TRACE\] P: portal=, stmt=" \
                 f"select \* from {self.table_name}"
        search_res = re.search(expect, shell_res, re.S)
        self.assertIsNotNone(search_res, f'执行失败:{text}')

    def tearDown(self):
        text = "-----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(text)
        drop_res = PrimarySh.execut_db_sql(
            f"drop table if exists {self.table_name};")
        self.logger.info(drop_res)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        cmd = f"rm -rf {self.new_log_dir} {self.target_path};echo $?;"
        self.logger.info(cmd)
        shell_res = self.common.get_sh_result(self.standby_root, cmd)
        self.assertEqual('0', shell_res.splitlines()[-1].strip(),
                         f'删除目录失败:{text}')
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'执行失败:{text}')
        self.assertTrue(restart_res, f'执行失败:{text}')
        self.assertTrue(result1 and result2 and result3, f'执行失败:{text}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
